import { defineStore } from 'pinia'
import { getDramaList, createDrama, deleteDrama, publishDrama, unpublishDrama, getDramaSeries, updateEpisode, createEpisode, deleteEpisode } from '@/api/drama'
import { ElMessage } from 'element-plus'

// 剧本状态管理
export const useDramaStore = defineStore('drama', {
  state: () => ({
    dramaList: [],
    total: 0,
    loading: false,
    currentPage: 1,
    pageSize: 10,
    
    // 分集相关
    episodeList: [],
    episodeLoading: false,
    currentDramaId: null
  }),
  
  getters: {
    hasDramas: (state) => state.dramaList.length > 0,
    getDramaById: (state) => (id) => {
      return state.dramaList.find(drama => drama.id === id)
    },
    hasEpisodes: (state) => state.episodeList.length > 0
  },
  
  actions: {
    // 获取剧本列表
    async fetchDramaList(params = {}) {
      try {
        this.loading = true
        // 清空当前列表，避免切换页面时旧数据和骨架屏同时显示
        this.dramaList = []
        
        const response = await getDramaList({
          page: this.currentPage,
          size: this.pageSize,
          ...params
        })
        
        // 适配新的API返回的数据结构
        if (response.data) {
          this.dramaList = response.data.list || []
          this.total = response.data.total || 0
        } else {
          this.dramaList = []
          this.total = 0
        }
        
        return Promise.resolve(response)
      } catch (error) {
        console.error('获取剧本列表失败:', error)
        return Promise.reject(error)
      } finally {
        this.loading = false
      }
    },
    
    // 清空剧本列表
    clearDramaList() {
      this.dramaList = []
      this.loading = true
    },
    
    // 创建剧本
    async createDrama(dramaData) {
      try {
        const { data } = await createDrama(dramaData)
        ElMessage.success('剧本创建成功')
        return Promise.resolve(data)
      } catch (error) {
        ElMessage.error('剧本创建失败')
        return Promise.reject(error)
      }
    },
    
    // 删除剧本
    async deleteDrama(id) {
      try {
        await deleteDrama(id)
        ElMessage.success('剧本删除成功')
        // 刷新列表
        this.fetchDramaList()
        return Promise.resolve()
      } catch (error) {
        ElMessage.error('剧本删除失败')
        return Promise.reject(error)
      }
    },
    
    // 发布剧本
    async publishDrama(id) {
      try {
        await publishDrama(id)
        ElMessage.success('剧本发布成功')
        // 刷新列表
        this.fetchDramaList()
        return Promise.resolve()
      } catch (error) {
        ElMessage.error('剧本发布失败')
        return Promise.reject(error)
      }
    },
    
    // 取消发布剧本
    async unpublishDrama(id) {
      try {
        await unpublishDrama(id)
        ElMessage.success('剧本取消发布成功')
        // 刷新列表
        this.fetchDramaList()
        return Promise.resolve()
      } catch (error) {
        ElMessage.error('剧本取消发布失败')
        return Promise.reject(error)
      }
    },
    
    // 更新分页
    updatePagination(page, size) {
      this.currentPage = page
      this.pageSize = size
      this.fetchDramaList()
    },
    
    // 获取分集列表
    async fetchEpisodeList(dramaId) {
      try {
        this.episodeLoading = true
        this.currentDramaId = dramaId
        
        const { data } = await getDramaSeries(dramaId)
        this.episodeList = data
        
        return Promise.resolve(data)
      } catch (error) {
        ElMessage.error('获取分集列表失败')
        return Promise.reject(error)
      } finally {
        this.episodeLoading = false
      }
    },
    
    // 更新分集
    async updateEpisode(episodeId, data) {
      if (!this.currentDramaId) return Promise.reject(new Error('剧本ID不存在'))
      
      try {
        const response = await updateEpisode(this.currentDramaId, episodeId, data)
        
        // 更新本地数据
        const index = this.episodeList.findIndex(item => item.id === episodeId)
        if (index !== -1) {
          this.episodeList[index] = response.data
        }
        
        ElMessage.success('分集更新成功')
        return Promise.resolve(response.data)
      } catch (error) {
        ElMessage.error('分集更新失败')
        return Promise.reject(error)
      }
    },
    
    // 创建分集
    async createEpisode(data) {
      if (!this.currentDramaId) return Promise.reject(new Error('剧本ID不存在'))
      
      try {
        const response = await createEpisode(this.currentDramaId, data)
        
        // 添加到本地列表
        this.episodeList.push(response.data)
        
        ElMessage.success('分集创建成功')
        return Promise.resolve(response.data)
      } catch (error) {
        ElMessage.error('分集创建失败')
        return Promise.reject(error)
      }
    },
    
    // 删除分集
    async deleteEpisode(episodeId) {
      if (!this.currentDramaId) return Promise.reject(new Error('剧本ID不存在'))
      
      try {
        await deleteEpisode(this.currentDramaId, episodeId)
        
        // 从本地列表移除
        const index = this.episodeList.findIndex(item => item.id === episodeId)
        if (index !== -1) {
          this.episodeList.splice(index, 1)
        }
        
        ElMessage.success('分集删除成功')
        return Promise.resolve()
      } catch (error) {
        ElMessage.error('分集删除失败')
        return Promise.reject(error)
      }
    },
    
    // 更新本地分集数据（不调用API）
    updateLocalEpisodeList(episodes) {
      this.episodeList = episodes
    }
  }
}) 